package cn.cqie.attendance.common.realm;

import cn.cqie.attendance.common.config.UserToken;
import cn.cqie.attendance.common.pojo.Student;
import cn.cqie.attendance.common.pojo.Teacher;
import cn.cqie.attendance.common.pojo.User;
import cn.cqie.attendance.common.service.LoginService;
import cn.cqie.attendance.common.util.JwtUtil;
import cn.cqie.attendance.common.util.LocalJwt;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token != null && getAuthenticationTokenClass().isAssignableFrom(token.getClass());
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {

        String token = (String) (authenticationToken).getCredentials();
        String username;
        // token是否有效
        if (Strings.isNullOrEmpty(token)
                || !JwtUtil.verify(token,
                (username = Objects.requireNonNull(LocalJwt.getCurrentUser(request))
                        .getUsername()))) {

            return null;
        }

        UserToken t = (UserToken) authenticationToken;

        User user = null;
        if ("student".equals(t.getRole())) {
            user = loginService.queryStudent(username);
            if (user == null || user.getStatus() == 0) {
                return null;
            }
            user.setTag("student");
        } else {
            user = loginService.queryTeacher(username);
            if (user == null) {
                return null;
            }
            if (((Teacher)user).getRole() == 0) {
                user.setTag("teacher");
            } else {
                user.setTag("admin");
            }
        }
        LocalJwt.setCurrentUser(request, user);
        return new SimpleAuthenticationInfo(user, token,
                ByteSource.Util.bytes(user.getId() + "team7"),
                getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    
}
